import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

import 'resources.dart';
import '/generated/l10n.dart' as l10n;

export 'utils/ColorUtils.dart';
export 'utils/ImageUtils.dart';
export 'utils/QzScreenUtil.dart';
export 'utils/GSpUtils.dart';
export 'utils/Toast.dart';
export 'app_routes.dart';
export 'utils/nav_utils.dart';
export '/generated/l10n.dart';

/// created by hcl
/// on 2023/5/29
/// page components
/// desc 公共组件

Future<bool> requestPermission(Permission permission) async {
  var permissionStatus = await permission.request();
  return permissionStatus == PermissionStatus.granted;
}

double get designWidth => QzScreenUtil.designWidth;

EdgeInsets get designPadding => QzScreenUtil.designPadding;

extension ScreenSizeDouble on double {
  double get ss => getScreenSize(this);
}

extension ScreenSizeInt on int {
  double get ss => getScreenSize(toDouble());
}

getScreenSize(double num) {
  return QzScreenUtil.qzsw(num);
}

RegExp passwordValidator = RegExp(r'^(?=.*\d)(?=.*[a-zA-Z]).{8,}$');

logout() {}

TextStyle getTextStyleFamily(Color color, double size,
    {FontWeight? fontWeight, String family = ''}) {
  return TextStyle(
      color: color,
      fontSize: size.ss,
      fontWeight: fontWeight ?? FontWeight.normal,
      fontFamily: family);
}

TextStyle getTextStyle(Color color, double size,
    {FontWeight? fontWeight, TextDecoration? textDecoration}) {
  return TextStyle(
      color: color,
      fontSize: size.ss,
      fontWeight: fontWeight ?? FontWeight.normal,
      decoration: textDecoration);
}

// extension TextStyleFamily on TextStyle {
//   TextStyle get lora => copyWith(fontFamily: 'Lora');
//
//   TextStyle get loraBold => copyWith(fontFamily: 'Lora-Bold');
//
//   TextStyle get urbanist => copyWith(fontFamily: 'Urbanist');
//
//   TextStyle get urbanistBold => copyWith(fontFamily: 'Urbanist-Bold');
// }

const FontWeight light = FontWeight.w300;
const FontWeight regular = FontWeight.w400;
FontWeight medium = isAndroid ? FontWeight.w600 : FontWeight.w500;
const FontWeight semibold = FontWeight.w600;
const FontWeight bold = FontWeight.w700;

TextStyle get normal012 => getTextStyle(ColorUtils.color_000000, 12);

TextStyle get normal014 => getTextStyle(ColorUtils.color_000000, 14);

TextStyle get normal016 => getTextStyle(ColorUtils.color_000000, 16);

TextStyle get normal312 => getTextStyle(ColorUtils.color_333333, 12);

TextStyle get normal314 => getTextStyle(ColorUtils.color_333333, 14);

TextStyle get normal316 => getTextStyle(ColorUtils.color_333333, 16);

TextStyle get normal31606 =>
    getTextStyle(ColorUtils.color_333333.withOpacity(0.6), 16);

TextStyle get normal318 => getTextStyle(ColorUtils.color_333333, 18);

TextStyle get normal612 => getTextStyle(ColorUtils.color_666666, 12);

TextStyle get normal712 => getTextStyle(ColorUtils.color_777777, 12);

TextStyle get normal714 => getTextStyle(ColorUtils.color_777777, 14);

TextStyle get normal716 => getTextStyle(ColorUtils.color_777777, 16);

TextStyle get normal718 => getTextStyle(ColorUtils.color_777777, 18);

TextStyle get normalAD12 => getTextStyle(ColorUtils.color_AD0000, 12);

TextStyle get normalF15 => getTextStyle(ColorUtils.color_FFFFFF, 15);

TextStyle get normalF18 => getTextStyle(ColorUtils.color_FFFFFF, 18);

TextStyle get medium018 =>
    getTextStyle(ColorUtils.color_000000, 18, fontWeight: FontWeight.w600);

TextStyle get mediumAD12 =>
    getTextStyle(ColorUtils.color_AD0000, 12, fontWeight: FontWeight.w600);

TextStyle get mediumAD15 =>
    getTextStyle(ColorUtils.color_AD0000, 15, fontWeight: FontWeight.w600);

TextStyle get mediumAD16 =>
    getTextStyle(ColorUtils.color_AD0000, 16, fontWeight: FontWeight.w600);

TextStyle get mediumF11 =>
    getTextStyle(ColorUtils.color_FFFFFF, 11, fontWeight: medium);

TextStyle get mediumF12 =>
    getTextStyle(ColorUtils.color_FFFFFF, 12, fontWeight: medium);

TextStyle get mediumF13 =>
    getTextStyle(ColorUtils.color_FFFFFF, 13, fontWeight: medium);

TextStyle get mediumF14 =>
    getTextStyle(ColorUtils.color_FFFFFF, 14, fontWeight: medium);

TextStyle get mediumF1407 =>
    getTextStyle(ColorUtils.color_FFFFFF.withOpacity(0.7), 14,
        fontWeight: medium);

TextStyle get mediumF15 =>
    getTextStyle(ColorUtils.color_FFFFFF, 15, fontWeight: medium);

TextStyle get semiboldApp12 =>
    getTextStyle(ColorUtils.app_color, 12, fontWeight: semibold);

TextStyle get semiboldF12 =>
    getTextStyle(ColorUtils.color_FFFFFF, 12, fontWeight: semibold);

TextStyle get boldF13 =>
    getTextStyle(ColorUtils.color_FFFFFF, 13, fontWeight: bold);

TextStyle get boldF14 =>
    getTextStyle(ColorUtils.color_FFFFFF, 14, fontWeight: bold);

TextStyle get boldF15 =>
    getTextStyle(ColorUtils.color_FFFFFF, 15, fontWeight: bold);

TextStyle get boldF16 =>
    getTextStyle(ColorUtils.color_FFFFFF, 16, fontWeight: bold);

TextStyle get boldF18 =>
    getTextStyle(ColorUtils.color_FFFFFF, 18, fontWeight: bold);

TextStyle get boldF20 =>
    getTextStyle(ColorUtils.color_FFFFFF, 20, fontWeight: bold);

TextStyle get semiboldF0714 =>
    getTextStyle(ColorUtils.color_FFFFFF.withOpacity(0.7), 14,
        fontWeight: semibold);

TextStyle get semiboldF13 =>
    getTextStyle(ColorUtils.color_FFFFFF, 13, fontWeight: semibold);

TextStyle get semiboldF14 =>
    getTextStyle(ColorUtils.color_FFFFFF, 14, fontWeight: semibold);

TextStyle get semiboldF15 =>
    getTextStyle(ColorUtils.color_FFFFFF, 15, fontWeight: semibold);

TextStyle get semiboldF16 =>
    getTextStyle(ColorUtils.color_FFFFFF, 16, fontWeight: semibold);

TextStyle get semiboldF17 =>
    getTextStyle(ColorUtils.color_FFFFFF, 17, fontWeight: semibold);

/// common

TextStyle get normal616 => getTextStyle(ColorUtils.color_666666, 16);

TextStyle get normal912 => getTextStyle(ColorUtils.color_999999, 12);

TextStyle get normal914 => getTextStyle(ColorUtils.color_999999, 14);

TextStyle get normalB114 => getTextStyle(ColorUtils.color_B1B1B1, 14);

TextStyle get normalC18 => getTextStyle(ColorUtils.color_CCCCCC, 18);

TextStyle get normalF12 => getTextStyle(ColorUtils.color_FFFFFF, 12);

TextStyle get normalF13 => getTextStyle(ColorUtils.color_FFFFFF, 13);

TextStyle get normalF14 => getTextStyle(ColorUtils.color_FFFFFF, 14);

TextStyle get normalF16 => getTextStyle(ColorUtils.color_FFFFFF, 16);

TextStyle get normalF24 => getTextStyle(ColorUtils.color_FFFFFF, 24);

TextStyle get medium014 =>
    getTextStyle(ColorUtils.color_000000, 14, fontWeight: medium);

TextStyle get medium314 =>
    getTextStyle(ColorUtils.color_333333, 14, fontWeight: medium);

TextStyle get medium316 =>
    getTextStyle(ColorUtils.color_333333, 16, fontWeight: medium);

TextStyle get medium318 =>
    getTextStyle(ColorUtils.color_333333, 18, fontWeight: medium);

TextStyle get medium3C14 =>
    getTextStyle(ColorUtils.color_3C6EF0, 14, fontWeight: medium);

TextStyle get mediumF16 =>
    getTextStyle(ColorUtils.color_FFFFFF, 16, fontWeight: medium);

///图片显示-文件图片
Image fileImage(
  String path, {
  double? width,
  double? height,
  fit = BoxFit.fill,
  placeholder = ImageUtils.default_image,
}) {
  return Image.file(File(path),
      width: width,
      height: height,
      fit: fit,
      errorBuilder: (ctx, err, stackTrace) =>
          assetImage(placeholder, width: width, height: height, fit: fit));
}

///图片显示
Image assetImage(
  String name, {
  double? width,
  double? height,
  fit = BoxFit.fill,
  placeholder = ImageUtils.default_image,
}) {
  return Image.asset('${ImageUtils.basePath}$name',
      width: width,
      height: height,
      fit: fit,
      errorBuilder: (ctx, err, stackTrace) =>
          assetImage(placeholder, width: width, height: height, fit: fit));
}

Widget cachedImage(
  String url, {
  double? width,
  double? height,
  fit = BoxFit.fill,
  placeholder = ImageUtils.default_image,
  Map<String, String>? httpHeaders,
}) {
  if (url.startsWith('http')) {
    return CachedNetworkImage(
      width: width,
      height: height,
      memCacheWidth: 800,
      memCacheHeight: 800,
      imageUrl: url,
      fit: fit,
      fadeInDuration: const Duration(seconds: 0),
      fadeOutDuration: const Duration(seconds: 0),
      placeholder: (BuildContext context, String url) {
        return const SizedBox();
      },
    );
  } else {
    return assetImage(placeholder, width: width, height: height, fit: fit);
  }
}

Image networkImage(
  String url, {
  double? width,
  double? height,
  fit = BoxFit.fill,
  placeholder = ImageUtils.default_image,
  Map<String, String>? httpHeaders,
}) {
  if (url.startsWith('http')) {
    return Image.network(url,
        width: width,
        height: height,
        fit: fit,
        errorBuilder: (ctx, err, stackTrace) =>
            assetImage(placeholder, width: width, height: height, fit: fit));
  } else {
    return assetImage(placeholder, width: width, height: height, fit: fit);
  }
}

///判断是否超过行数
bool textExceedMaxLines(
    String text, TextStyle textStyle, int maxLine, double maxWidth) {
  TextSpan textSpan = TextSpan(text: text, style: textStyle);
  TextPainter textPainter = TextPainter(
      text: textSpan, maxLines: maxLine, textDirection: TextDirection.ltr);
  textPainter.layout(maxWidth: maxWidth);
  if (textPainter.didExceedMaxLines) {
    return true;
  }
  return false;
}

Widget commonTitleBar(String title,
    {VoidCallback? onTap,
    Color titleBackColor = ColorUtils.app_color,
    Widget leftAction = const SizedBox(),
    Widget rightAction = const SizedBox()}) {
  return Container(
    padding: EdgeInsets.only(top: QzScreenUtil.designPadding.top),
    color: titleBackColor,
    child: SizedBox(
      width: designWidth.ss,
      height: 48.ss,
      child: Stack(
        children: [
          Center(
            child: Text(title,
                style: semiboldF17,
                maxLines: 1,
                overflow: TextOverflow.ellipsis),
          ),
          Row(
            children: [
              onTap != null
                  ? InkWell(
                      onTap: onTap,
                      radius: Material.defaultSplashRadius,
                      child: Container(
                        width: getScreenSize(50),
                        height: getScreenSize(50),
                        alignment: Alignment.center,
                        child: assetImage(ImageUtils.back,
                            width: getScreenSize(35),
                            height: getScreenSize(35)),
                      ),
                    )
                  : const SizedBox(),
              leftAction,
              const Spacer(),
              rightAction
            ],
          ),
        ],
      ),
    ),
    // : assetImage(ImageUtils.wst_logo, width: 30.ss, height: 30.ss),
  );
}

Widget commonButton(VoidCallback onTap, String text, {bool isConfirm = true}) {
  return InkWell(
    onTap: onTap,
    child: Container(
      height: 42.ss,
      alignment: Alignment.center,
      margin: EdgeInsets.all(12.ss),
      decoration: BoxDecoration(
          color: isConfirm ? ColorUtils.color_AD0000 : ColorUtils.color_F5F5F5,
          borderRadius: BorderRadius.circular(10.ss)),
      child: Text(text, style: isConfirm ? normalF18 : normal718),
    ),
  );
}

Widget commonGetCode(Function() onTap, String text, {bool isDark = true}) {
  return InkWell(
    onTap: onTap,
    child: Container(
      width: 120.ss,
      alignment: Alignment.center,
      child: Text(text, style: mediumAD16),
    ),
  );
}

Row commonRow(
  String title,
  String value, {
  String unit = '',
  bool isBlack = true,
}) {
  return Row(
    children: [
      SizedBox(
        width: 100.ss,
        child: Text(title,
            style: isBlack ? normal316 : normalF16, textAlign: TextAlign.right),
      ),
      Expanded(
        child: Text(value,
            style: isBlack ? normal316 : normalF16, textAlign: TextAlign.right),
      ),
      Text(unit, style: isBlack ? normal316 : normalF16),
    ],
  );
}

Widget queryRow(String title1, String title2) {
  return Container(
    padding: EdgeInsets.all(5.ss),
    child: Row(
      children: [
        Expanded(
          child: Text(title1, textAlign: TextAlign.center),
        ),
        Expanded(
          child: Text(title2, textAlign: TextAlign.center),
        ),
      ],
    ),
  );
}

void showPicker(BuildContext context, DateTime initDate,
    Function(DateTime result) onResult) {
  showDatePicker(
          context: context,
          locale: GSpUtils.zh,
          initialDate: initDate,
          firstDate: DateTime.fromMillisecondsSinceEpoch(
              DateTime.now().millisecondsSinceEpoch -
                  50 * 365 * 24 * 3600 * 1000),
          lastDate: DateTime.now())
      .then((value) {
    if (value != null) {
      onResult(value);
    }
  });
}

void showPickerRange(
    BuildContext context,
    DateTime initStartDate,
    DateTime initEndDate,
    Function(DateTime startResule, DateTime endResult) onResult) {
  showDateRangePicker(
          context: context,
          locale: GSpUtils.zh,
          initialEntryMode: DatePickerEntryMode.calendarOnly,
          initialDateRange:
              DateTimeRange(start: initStartDate, end: initEndDate),
          firstDate: DateTime.fromMillisecondsSinceEpoch(
              DateTime.now().millisecondsSinceEpoch -
                  50 * 365 * 24 * 3600 * 1000),
          lastDate: DateTime.now())
      .then((value) {
    if (value != null) {
      onResult(value.start, value.end);
    }
  });
}

Widget commonDrop(String hint, String? result, List<String> list,
    Function(String? value) changed,
    {bool isSmall = false, bool isDark = true}) {
  Color borderColor =
      isDark ? ColorUtils.color_FFFFFF : ColorUtils.color_B1B1B1;
  TextStyle contentStyle = isDark ? normalF14 : normal714;
  return Container(
    margin: EdgeInsets.symmetric(horizontal: 5.ss),
    padding: EdgeInsets.only(left: isSmall ? 5.ss : 25.ss, right: 5.ss),
    decoration: BoxDecoration(
        border: Border.all(color: borderColor),
        borderRadius: BorderRadius.circular(10.ss)),
    child: DropdownButton<String>(
      isExpanded: true,
      underline: const SizedBox(),
      hint: Center(
        child: Text(hint, style: contentStyle),
      ),
      value: result,
      items: list.map((value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Center(
            child: Text(value, style: contentStyle),
          ),
        );
      }).toList(),
      onChanged: changed,
      dropdownColor: isDark ? ColorUtils.color_80CE9B : ColorUtils.color_FFFFFF,
      iconEnabledColor: borderColor,
      iconDisabledColor: borderColor,
    ),
  );
}

Widget commonDrop2(String hint, String? result, List<String> list,
    Function(String? value) changed,
    {bool isSmall = false, bool isLeft = false, Icon? icon}) {
  return Container(
    margin: EdgeInsets.symmetric(horizontal: 5.ss),
    padding: EdgeInsets.only(left: isSmall ? 5.ss : 25.ss, right: 5.ss),
    child: DropdownButton<String>(
      isExpanded: true,
      underline: const SizedBox(),
      hint: Container(
        alignment: isLeft ? Alignment.centerLeft : Alignment.center,
        child: Text(hint, style: normal914),
      ),
      value: result,
      items: list.map((value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Container(
            alignment: isLeft ? Alignment.centerLeft : Alignment.center,
            child: Text(value, style: normal314),
          ),
        );
      }).toList(),
      onChanged: changed,
      icon: icon,
    ),
  );
}

Widget commonDropColor(String hint, String? result, List<String> list,
    Function(String? value) changed) {
  return DropdownButton<String>(
    underline: const SizedBox(),
    hint: Center(
      child: Text(hint, style: normal714),
    ),
    value: result,
    items: list.map((value) {
      return DropdownMenuItem<String>(
        value: value,
        child: Center(child: Text(value, style: normal714)),
      );
    }).toList(),
    onChanged: changed,
    icon: const SizedBox(),
  );
}

///更多颜色 color_44C79D
Widget recordRow(String title, String value, String unit, String state,
    {Color stateColor = ColorUtils.color_333333, double stateSize = 12}) {
  return Row(
    children: [
      Text(title, style: normal912),
      Expanded(
        child: Text(value, style: normal612),
      ),
      Text(unit, style: normal912),
      Text(state,
          style: TextStyle(
              color: stateColor,
              fontSize: stateSize,
              fontWeight: FontWeight.normal)),
    ],
  );
}

String realGenDir = '/storage/emulated/0';
String uuidDir = '/storage/emulated/0/download/uuid';

class NormalModel {
  String title = '';
  String des = '';

  NormalModel(this.title, this.des);
}

const String BACK_CODE = 'backCode';
const String BACK_DATA = 'data';
const int NORMAL_CODE = 0;
const int SUCESS_CODE = 1;
const int SCAN_CODE = 3;

Map<String, dynamic> backResult(int backCode, dynamic data) {
  return {BACK_CODE: backCode, BACK_DATA: data};
}

BuildContext get appContext => _appContext();

BuildContext _appContext() {
  return Nav.globalNavigatorKey.currentState!.context;
}

l10n.S get word => _appWord();

l10n.S _appWord() {
  return l10n.S.of(appContext);
}

bool _isWeb() {
  return kIsWeb == true;
}

bool _isAndroid() {
  return _isWeb() ? false : Platform.isAndroid;
}

bool _isIOS() {
  return _isWeb() ? false : Platform.isIOS;
}

bool _isMacOS() {
  return _isWeb() ? false : Platform.isMacOS;
}

bool _isWindows() {
  return _isWeb() ? false : Platform.isWindows;
}

bool _isFuchsia() {
  return _isWeb() ? false : Platform.isFuchsia;
}

bool _isLinux() {
  return _isWeb() ? false : Platform.isLinux;
}

bool get isWeb => _isWeb();

bool get isAndroid => _isAndroid();

bool get isIOS => _isIOS();

bool get isMacOS => _isMacOS();

bool get isWindows => _isWindows();

bool get isFuchsia => _isFuchsia();

bool get isLinux => _isLinux();
